<?php
/**
 * Created by PhpStorm.
 * User: Asnyc
 * Date: 2017/12/18
 * Time: 15:25
 */

namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    protected $code;
    protected $msg;
    protected $errorCode;

    /**
     * @param Exception $e
     * @return \think\response\Json
     * request_url 当前请求URL
     * 全局异常处理func
     */
    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            //如果是自定义异常的话
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            //如果调试模式开启
            if(config('app_debug')){
                return parent::render($e); //还原默认异常
                $this->recordErrorLog($e);
            }else{
                $this->code = 500;
                $this->msg = '服务器内部错误,原因不告诉你٩(๑❛ᴗ❛๑)۶';
                $this->errorCode = 999;
            }
        }
        //获取请求信息
        $request = Request::instance();
        $result = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'request_url' => $request->url()
        ];
        return json($result,$this->code);
    }

    /**
     * @param Exception $e
     * 记录错误日志func
     * Log::init 日志初始化
     * Log::record 记录日志
     */
    private function recordErrorLog(Exception $e){
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);
        Log::record($e->getMessage(),'error');
    }
}